<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="./node_modules/axios/dist/axios.js"></script>
    <script>
        function send(url) {
            return axios.get(url);
        }
        // send(10).then(res => console.log(res.data));
        let arr = new Array(100).fill((Math.random()))
        let urls = arr.map(item => `http://localhost:8080?a=${item}`);
        // console.log(urls)
        multiRequest(urls, 3)
        .then(allRes => {
            console.log(allRes.map(res => res.data))
        })
        function multiRequest(urls = [], maxNum) {
            console.log(urls)
            // 请求总数量
            const len = urls.length;
            // 根据请求数量创建一个数组来保存请求的结果
            const result = new Array(len).fill(false);
            // 当前完成的数量
            let count = 0;

            return new Promise((resolve, reject) => {
                // 请求maxNum个
                while (count < maxNum) {
                    next();
                }

                function next() {
                    let current = count++;
                    // 处理边界条件
                    if (current >= len) {
                        // 请求全部完成就将promise置为成功状态, 然后将result作为promise值返回
                        !result.includes(false) && resolve(result);
                        return;
                    }
                    const url = urls[current];
                    console.log(`开始 ${current}`, new Date().toLocaleString());
                    send(url)
                        .then((res) => {
                            // console.log(res);
                            // 保存请求结果
                            result[current] = res;
                            console.log(`完成 ${current}`, new Date().toLocaleString());
                            // 请求没有全部完成, 就递归
                            if (current < len) {
                                next();
                            }
                        })
                        .catch((err) => {
                            // console.log(err)
                            console.log(`结束 ${current}`, new Date().toLocaleString());
                            result[current] = err;
                            // 请求没有全部完成, 就递归
                            if (current < len) {
                                next();
                            }
                        });
                }
            });
        }
    </script>
</body>

</html>